前面我们讲了怎么通过参数的属性限制参数的个数和长度。今天我们来看看,通过参数的属性,限制参数的格式以及参数的可选集(特定的值)。
首先我们来看看今天的示例脚本:
function test-net_port {
[cmdletbinding()]
param(
[parameter(mandatory=$true,Helpmessage="Enter the name of a computer to check connectivity to.")]
[ValidateCount(1,5)]
[ValidateLength(1,15)]
[ValidatePattern("SZ[A-Z]{2,3}\d{1,2}$")] #computerName 必须要满足正则表达式
[string[]]$computerName,
[parameter(mandatory=$false)]
[ValidateSet(80,443,22)] # port 的值,只能是 80,443 和 22 其中的一个
[int] $port
)
foreach ($computer in $computerName) {
Write-Verbose "Now testing $computer."
if ($port -eq "")
{
$ping = Test-NetConnection -ComputerName $computer -InformationLevel Quiet -WarningAction SilentlyContinue
} else {
$ping = Test-NetConnection -ComputerName $computer -InformationLevel Quiet -WarningAction SilentlyContinue -Port $port
}
if ($ping){
Write-Output $ping
} else {
Write-Verbose "Ping failed on $computer. Check the network connection."
Write-Output $ping
}
}
}
运作结果:
PS C:\Users> test-net_port -computerName SZSVR1
False
PS C:\Users> test-net_port -computerName SZSVR001
test-net_port : Cannot validate argument on parameter 'computerName'. The argument "SZSVR001" does not match the "SZ[A-Z]{2,3}\d{1,2}$" pattern. Supply an argument that matches
"SZ[A-Z]{2,3}\d{1,2}$" and try the command again.
At line:1 char:29
+ test-net_port -computerName SZSVR001
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [test-net_port], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,test-net_port
PS C:\Users> test-net_port -computerName SZSVR01 -port 23
test-net_port : Cannot validate argument on parameter 'port'. The argument "23" does not belong to the set "80,443,22" specified by the ValidateSet attribute. Supply an argument that is in
the set and then try the command again.
At line:1 char:43
+ test-net_port -computerName SZSVR01 -port 23
+ ~~
+ CategoryInfo : InvalidData: (:) [test-net_port], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,test-net_port
PS C:\Users> test-net_port -computerName SZSVR01 -port 22